package com.fanfan.shiroadmin.modules.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fanfan.shiroadmin.common.exception.ServiceRuntimeException;
import com.fanfan.shiroadmin.common.utils.RedisKeysUtil;
import com.fanfan.shiroadmin.common.utils.RedisUtil;
import com.fanfan.shiroadmin.modules.sys.auth.TokenGenerator;
import com.fanfan.shiroadmin.modules.sys.constant.SysConstant;
import com.fanfan.shiroadmin.modules.sys.entity.SysUserEntity;
import com.fanfan.shiroadmin.modules.sys.service.IShiroService;
import com.fanfan.shiroadmin.modules.sys.service.ISysMenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @author DunFan.Liao
 * @date 2021/12/27 15:46
 */
@Service(IShiroService.BEAN_ID)
public class ShiroServiceImpl implements IShiroService
{
    @Autowired
    private RedisUtil redisUtil;

    /**
     * sessionNamespace redis用户会话的命名空间
     */
    @Value("${redis.spring.session.namespace}")
    private String sessionNamespace;


    @Override
    public JSONObject createToken(SysUserEntity user) throws ServiceRuntimeException
    {
        // 1.生成token对象
        String token = TokenGenerator.generateValue();
        // 2.设置当前账号token
        String tokenUserKey = RedisKeysUtil.getTokenUserKey(sessionNamespace,user.getUserAcct());
        redisUtil.set(tokenUserKey,token);
        // 3.redis token set user data，
        String onlineUserKey = RedisKeysUtil.getOnlineUserKey(sessionNamespace,token);
        redisUtil.get(onlineUserKey,0);
        redisUtil.set(onlineUserKey,user);
        JSONObject result = new JSONObject();
        result.put("token",token);
        // 3.返回token
        return result;
    }

    @Override
    public JSONObject queryUserByToken(String token) throws ServiceRuntimeException
    {
        // 获取当前登录token的用户信息
        String onlineUserKey = RedisKeysUtil.getOnlineUserKey(sessionNamespace,token);
        SysUserEntity sysUserEntity = redisUtil.get(onlineUserKey, SysUserEntity.class, -1);
        if (sysUserEntity != null)
        {
            JSONObject result = new JSONObject();
            result.put("user",sysUserEntity);
            return result;
        }
        return new JSONObject();
    }

    @Override
    public JSONObject getStringPermissions(Long userId) throws ServiceRuntimeException
    {

        return null;
    }


    public static void main(String[] args)
    {
//        SysUserEntity user = new SysUserEntity();
//        user.setPhoneSms("1111");
//        JSONObject result = new JSONObject();
//        result.put("user",user);
//        System.out.println(result);
        System.out.println( String.format("%s@%s", "", "sys/menuconf"));
    }
}
